package vn.edu.uit.wifi_transfering;

/**
 * Thiet bi su dung lop nay de tao ServerSocket
 * Khi do, thiet bi se tro thanh Server
 * @author Le Xuan Vu
 *
 */

import java.io.IOException;
import java.net.ServerSocket;

public class TCPServer implements Runnable{

	private ServerSocket serverSocket;
	private Thread thread;
	private static TCPServer server;
	
	private TCPServer() {
		
	}
	
	public static TCPServer getInstance() {
		if (server == null) {
			server = new TCPServer();
		}
		
		return server;
	}
	
	public boolean start() {
		try {
			serverSocket = new ServerSocket(12345);
			System.out.println("Wating for clients...");
			thread = new Thread(this);
			thread.start();
			while(!thread.isAlive()) {
				//
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}
	
	public boolean stop() {
		try {
			serverSocket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}
	
	public void run() {
		// TODO Auto-generated method stub
		while(true) {
			try {
				new ClientThread(serverSocket.accept()).start();				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}

